<template>
  <div class="customer-card">
    <div v-if="props.custStatus == 2" class="tip-box">流失</div>
    <div v-if="props.custStatus == 3" class="tip-box">异常</div>
    <div class="main-box">
      <div class="user-box">
        <div class="user-info">
          <div v-if="props.baseInfo.is_protected == 1" class="is-protect">已保护</div>
          <el-image :src="props.baseInfo.cust_baseinfo?.avatar" fit="cover" class="photo">
            <template #error>
              <el-icon><icon-picture /></el-icon>
            </template>
          </el-image>
          <div class="user_info_title">
            <div class="user_name">{{ props.baseInfo?.name }}</div>
            <div class="tel">{{ props.baseInfo?.mobile }}</div>
          </div>
        </div>
        <div v-if="props.baseInfo?.remark" class="user_desc_box">
          <div class="user_desc">{{ props.baseInfo?.remark }}</div>
        </div>
        <el-divider v-if="props.baseInfo?.remark" class="divider" />
        <div class="user_tag">
          <Tags v-if="props?.tagInfo.length > 0" :tags="props.tagInfo" />
          <span v-else class="no_tag">暂无标签</span>
          <el-icon @click="onCommand(3)" class="edit_icon"><Edit /></el-icon>
        </div>
        <el-divider class="divider" />
      </div>
      <el-tabs v-model="activeName" class="demo_tabs" @tab-change="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <div v-for="(item, index) in props.bodyInfo" :key="index" class="user-info-desc">
            <label class="title">{{ item.name }}：</label>
            <p class="word" v-if="item.type && item.type == 'qwPhone'">
              <span class="word" v-for="p in item.val" :key="p">{{ p }}</span>
            </p>
            <p class="word" v-else>
              <p v-if="item?.val instanceof Array && item?.val.length != 0" v-for='i in item.val' :key="i">
                <span>{{i.item ? i.item : i}}</span>
                <img v-show="i.isQw && i.isQw ==1" class="qwImg" src="@/assets/icon/qiyeweixin-icon.png" alt=""/>
              </p>
              <span v-else>{{ item.val || '--'}}</span>
              <!-- <span v-else>--</span> -->
            </p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="企业信息" name="second">
          <div v-for="(item, index) in props?.cust_corp_info" :key="index" class="user-info-desc">
            <label class="title">{{ item.name }}：</label>
            <span v-if="item.name != '营业执照'" class="word">{{ item?.value || '--' }}</span>
            <el-image v-else class="avatar" :src="item?.value" :preview-src-list="[item?.value]" :preview-teleported="true" fit="cover">
              <template #error>
                <el-icon><icon-picture /></el-icon>
              </template>
            </el-image>
          </div>
        </el-tab-pane>
        <el-tab-pane name="third">
          <template #label><el-badge class="contact_num" :value="contractList.length">联系人</el-badge></template>
          <div v-for="(item, index) in contractList" class="contract_box" :key="index">
            <el-image class="avator_icon" :src="item.avatar">
              <template #error
                ><el-icon><icon-picture /></el-icon
              ></template>
            </el-image>
            <div class="contrat_info">
              <div class="contrat_name">
                <span>{{ item.name }}</span>
                <el-image class="wechat_icon" :src="`/static/customer/wechat_${item.add_status}.png`"></el-image>
                <span>{{ ['未添加', '已添加', '申请中'][item.add_status] }}</span>
              </div>
              <div class="contrat_title">{{ item.mobile }}</div>
            </div>
            <div class="contrat_opera">
              <el-icon @click="delContact(item)" class="del_icon" v-if="index != 0"><Delete /></el-icon>
              <el-icon @click="editContact(item, index + 1)"><Edit /></el-icon>
            </div>
          </div>
          <!-- 编辑联系人、新加联系人 -->
          <el-card v-if="showContact" class="add_contact_box mt20" shadow="never">
            <template #header>
              <div class="card_header">
                <span>联系人{{ contact_num }}</span>
                <el-icon class="del_icon" @click="cancel"><CircleClose /></el-icon>
              </div>
            </template>
            <el-form class="contract_form" ref="contactRef" :model="contact" :rules="contactRules" label-width="75px" label-position="left">
              <el-form-item label="姓名" prop="name">
                <el-input type="text" v-model="contact.name" placeholder="请输入姓名" maxlength="5"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input type="text" v-model="contact.mobile" placeholder="请输入手机号" maxlength="11"></el-input>
              </el-form-item>
              <el-form-item label="">
                <el-button type="primary" @click="submit(contactRef)">保存</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-button class="contact_btn" plain @click="addContact" :disabled="contractList.length == 5">添加联系人</el-button>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog v-model="showDialog" :title="dialogData.title" width="30%" destroy-on-close center>
      <div>
        <el-input v-model="dialogData.val" :maxlength="dialogData.maxlength" placeholder="请输入" clearable />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="onCommit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 批量标签弹框 -->
    <BatchLabel ref="BatchLabelRef" @save="getTagsFun" />
    <!-- 选择员工 -->
    <ZWDepart ref="DepartRef" @submit="getZWDepartData" />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, watch, onMounted, nextTick } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useRoute } from 'vue-router'
  import { Picture as IconPicture } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { formatTel, getSetionId, IsNotEmpty } from '@/utils/utils'
  import { validatePhone, validateAcount } from '@/utils/validate'
  import Tags from './Tags.vue'
  import BatchLabel from '@/components/BatchLabel.vue'
  import ZWDepart from '@/components/ZWDepart.vue'

  import { setUpdateCustomer, batchAddTag, batchRmTag, batchAssignStaff, corpContacts, handleCorpContacts, delCorpContacts } from '@/api/customerCenter'

  import { useStore } from '@/store'
  const route = useRoute()

  interface Props {
    custStatus: any
    baseInfo: any
    tagInfo: any
    bodyInfo: any
    touchModeList: any
    cust_corp_info: any
  }

  const props = withDefaults(defineProps<Props>(), {
    custStatus: 1,
    baseInfo: {
      avatar: '',
      name: '',
      nickname: '',
      sex: 1,
      mobile: '',
      remark: ''
    },
    tagInfo: [], // 无数据
    bodyInfo: [],
    touchModeList: {},
    cust_corp_info: {}
  })
  const emit = defineEmits(['refresh', 'submit'])
  const store = useStore()
  const showDialog = ref(false)
  const BatchLabelRef = ref(null)
  const DepartRef = ref(null)
  const contactRef = ref<FormInstance>()
  const activeName = ref('third')
  const state = reactive({
    contact: Array<{ iconUrl: string | undefined; iconUrlDisabled: string | undefined; info: any }>()
  })
  const showContact = ref(false) //联系人创建
  const isEditContact = ref(false) // 编辑联系人
  const contact_id = ref(0) // 联系人
  const contact_info = ref({})
  const contact_num = ref(1)
  const contact = reactive({
    name: '',
    mobile: ''
  })
  const contractList = ref([])
  const checkName = (rule: any, value: any, callback: any) => {
    if (!value) {
      callback(new Error('姓名不能为空'))
    } else if (validateAcount(value)) {
      callback(new Error('姓名不正确'))
    } else {
      callback()
    }
  }
  const checkPhone = (rule: any, value: any, callback: any) => {
    if (!value) {
      callback(new Error('手机号码不能为空'))
    } else if (validatePhone(value)) {
      callback(new Error('手机号码不正确'))
    } else {
      callback()
    }
  }
  const contactRules = reactive<FormRules>({
    name: { required: true, validator: checkName, trigger: ['change', 'blur'] },
    mobile: { required: true, validator: checkPhone, trigger: ['change', 'blur'] }
  })
  let dialogData: any = reactive({
    type: '',
    title: '',
    maxlength: 6,
    val: ''
  })
  const baseInfo = reactive([
    { name: '客户阶段：', value: '' },
    { name: '客户来源：', value: '' },
    { name: '地区：', value: '' },
    { name: '地址：', value: '' },
    { name: '电子邮件：', value: '' },
    { name: '行业：', value: '' },
    { name: '添加时间：', value: '' },
    { name: '最近联系员工：', value: '' },
    { name: '最近联系时间：', value: '' },
    { name: '最近购买时间：', value: '' }
  ])
  const companyInfo = reactive([
    { name: '企业全称：', value: '' },
    { name: '企业简称：', value: '' },
    { name: '企业税号：', value: '' },
    { name: '地址：', value: '' },
    { name: '电子邮件：', value: '' },
    { name: '行业类型：', value: '' },
    { name: '行业规模：', value: '' },
    { name: '客户类型：', value: '' },
    { name: '营业执照：', value: '' },
    { name: '添加时间：', value: '' }
  ])

  // 添加联系人
  const addContact = () => {
    contact_num.value = contractList.value.length + 1
    showContact.value = true
    isEditContact.value = false
    contact.name = ''
    contact.mobile = ''
  }
  // 取消联系人
  const cancel = (val?: any) => {
    contact.name = ''
    contact.mobile = ''
    showContact.value = false
    contactRef.value.resetFields()
    contact_info.value = {}
  }
  // 保存联系人
  const submit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid: boolean) => {
      if (valid) {
        let params = {
          ...contact,
          cust_id: route.query?.id
        }
        isEditContact.value ? (params.contact_id = contact_id.value) : ''
        const res: any = await handleCorpContacts(params)
        ElMessage.success(`${isEditContact.value ? '编辑' : '添加'}联系人成功！`)
        isEditContact.value ? cancel(contact_info.value) : cancel()
        getCorpContact()
      }
    })
  }
  // 删除联系人
  const delContact = async (val: any) => {
    await delCorpContacts({
      cust_id: route.query?.id,
      contact_id: val.id
    })
    ElMessage.success('删除联系人成功！')
    getCorpContact()
  }
  // 编辑联系人
  const editContact = (val: any, index: number) => {
    contact_num.value = index
    showContact.value = true
    isEditContact.value = true
    contact.name = val.name
    contact.mobile = val.mobile
    contact_id.value = val.id
    contact_info.value = val
  }
  const handleClick = (val: any) => {
    activeName.value = val
  }

  // 批量打标签
  const batchAddTagFun = (param: object) => {
    batchAddTag(param).then((r: object) => {
      emit('refresh')
    })
  }
  // 批量删除标签
  const batchRmTagFun = (param: object) => {
    batchRmTag(param).then((r: object) => {
      emit('refresh')
    })
  }
  // 打开选择标签弹框
  const openBatchLabel = () => {
    BatchLabelRef.value.dialogData.labelChooseType = 1
    BatchLabelRef.value.dialogData.delname = '移除'
    if (props.tagInfo.length > 0) {
      BatchLabelRef.value.chooseDataArr = JSON.parse(JSON.stringify(props.tagInfo))
    }
    BatchLabelRef.value.dialogVisible = true
  }
  // 获取当前选中的标签数据
  const getTagsFun = (val: any) => {
    let param = {
      customer_list: [props.baseInfo.id],
      tag_list: val.idList
    }
    //  3批量打标签  4 批量删除标签
    if (val.labelType == 3) {
      batchAddTagFun(param)
      return
    }
    if (param.tag_list.length == 0) {
      ElMessage.warning('至少选择一个标签！')
      return
    }
    batchRmTagFun(param)
  }

  // 批量分配员工
  const batchAssignStaffFun = (work_user_list: any) => {
    batchAssignStaff({ customer_list: [props.baseInfo.id], work_user_list })
      .then((r: object) => {
        emit('refresh')
      })
      .catch((e: object) => {
        console.log(e, 555)
      })
  }
  //打开 选择员工弹框
  const openDepart = () => {
    DepartRef.value.departVisble = true
    DepartRef.value.appDialog.multiple = false
    if (props.baseInfo.assign_employees.id) {
      DepartRef.value.appDialog.chooseArr = [props.baseInfo.assign_employees.id]
    }
    DepartRef.value.appDialog.isInit = true
  }
  // 获取当前选中的员工的数据
  const getZWDepartData = (val: any) => {
    batchAssignStaffFun(getSetionId('id', val))
  }

  const onCommand = (e: string | number | object) => {
    const _i = Number(e) - 1
    if (e < 3) {
      showDialog.value = true
      dialogData.type = ['nickname', 'remark'][_i]
      dialogData.title = ['编辑昵称', '编辑备注'][_i]
      dialogData.maxlength = [6, 100][_i]
      dialogData.val = [props.baseInfo.nickname, props.baseInfo.remark][_i]
    } else {
      // 添加标签 或者删除标签
      if (e == 3) {
        openBatchLabel()
        return
      }
      openDepart()
      // 触发添加标签和重新分配操作
    }
  }

  const onCommit = (e: string | number | object) => {
    setUpdateCustomer({ customer_id: route.query.id, field: dialogData.type, content: dialogData.val }).then((res: any) => {
      showDialog.value = false
      props.baseInfo[dialogData.type] = dialogData.val // 静默更新
    })
  }
  // 获取联系人列表
  const getCorpContact = async () => {
    const res: any = await corpContacts({ cust_id: route.query?.id })
    contractList.value = res
    emit('submit', contractList.value)
  }
  onMounted(() => {
    getCorpContact()
  })
</script>

<style lang="scss" scoped>
  .customer-card {
    position: relative;
    .tip-box {
      height: 16px;
      background-color: #ffc69e;
      text-align: center;
      font-size: 12px;
      font-weight: 500;
      color: #ffffff;
      line-height: 16px;
    }
    .main-box {
      padding: 10px 20px;
      .user-box {
      .is-protect {
        position: absolute;
        z-index: 99;
        top: 0;
        left: 0;
        width: 50px;
        line-height: 20px;
        text-align:center;
        font-size: 12px;
        border-radius: 3px;
        background-color: #f8bf98;
        color: #ff6b00
      }
        .edit_icon {
          font-size: 18px;
          cursor: pointer;
          vertical-align: middle;
          margin-left: 10px;
        }
        .user-info {
          overflow: hidden;
          display: inline-flex;
          .photo {
            width: 60px;
            height: 60px;
            .el-image__inner {
              width: 60px;
              height: 60px;
            }
            .image-slot {
              .el-icon {
                font-size: 36px;
              }
            }
          }
          .user_info_title {
            flex: 1;

            margin-left: 20px;
            .user_name {
              font-size: 20px;
              font-family: STHeitiSC-Medium, STHeitiSC;
              font-weight: 500;
              color: #33302d;
              line-height: 25px;
            }
            .tel {
              margin-top: 10px;
              font-size: 14px;
              font-family: STHeitiSC-Light, STHeitiSC;
              font-weight: 300;
              color: #696969;
            }
          }
          .name_edit {
            float: right;
          }
        }
        .user_desc_box {
          margin-top: 20px;
          height: 48px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .user_desc {
            width: 227px;
            height: 100%;
            font-size: 13px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #969696;
            line-height: 16px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
          }
        }
        .user_tag {
          margin-top: 10px;
          display: flex;
          align-items: center;
          .no_tag {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #848484;
            line-height: 18px;
          }
        }
      }
      .demo_tabs {
        :deep(.el-tabs__nav-wrap) {
          &::after {
            height: 0;
          }
        }
        :deep(.el-tabs__content) {
          min-height: 300px;
        }
      }
      .contact_num {
        // --el-badge-radius: 5px;
        // --el-badge-padding: 5px;
        // --el-badge-size: 12px;
        :deep .el-badge__content.is-fixed {
          top: 8px;
        }
      }

      .omit-text {
        margin: 16px 0;
        font-size: 13px;
        font-weight: 300;
        color: #969696;
        line-height: 18px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .divider {
        margin: 16px 0;
      }
      .contact-us {
        display: flex;
        justify-content: space-around;
        align-items: center;
        width: 100%;
        height: 38px;
        margin-top: 16px;
        background: #fffaf9;
        border-radius: 19px;
        border: 1px solid #ffc69e;

        .item-box {
          width: 26px;
          height: 26px;
          background-color: #fff;
          border-radius: 50%;
          box-shadow: 0px 2px 4px 0px rgba(209, 209, 209, 0.5);

          .handle {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 26px;

            .handle-icon {
              width: 60%;
            }
          }
        }
      }
      .user-info-desc {
        display: flex;
        margin-bottom: 16px;

        &:last-of-type {
          margin-bottom: 0;
        }
        .avatar {
          width: 50px;
          height: 50px;
        }
        .title {
          flex: 0 0 auto;
          font-size: 14px;
          font-weight: 300;
          color: #969696;
        }
        .word {
          flex: auto;
          font-size: 14px;
          font-weight: 300;
          color: #33302d;
        }
      }
      .contract_box {
        overflow: hidden;
        padding-top: 14px;
        padding-bottom: 16px;
        border-bottom: 1px solid #eaeaea;
        .avator_icon {
          float: left;
          width: 36px;
          height: 36px;
          border-radius: 4px;
          margin-right: 10px;
        }
        .contrat_info {
          float: left;
          font-size: 14px;
          font-family: STHeitiSC-Light, STHeitiSC;
          font-weight: 300;
          color: #33302d;
          .contrat_name {
            display: flex;
            align-items: center;
            .wechat_icon {
              width: 16px;
              margin: 0px 10px;
            }
          }
          .contrat_title {
            margin-top: 10px;
            font-size: 12px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #969696;
          }
        }
        .contrat_opera {
          float: right;
          .del_icon {
            margin: 0 5px;
            cursor: pointer;
          }
        }
      }
      .add_contact_box {
        // margin-top: 20px;
        width: (100% -2px);
        // height: 246px;
        background: #ffffff;
        border: 1px solid #eaeaea;
        .card_header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          font-family: STHeitiSC-Medium, STHeitiSC;
          font-weight: 500;
          color: #33302d;
          .del_icon {
            font-size: 18px;
          }
        }
        :deep(.el-card__body) {
          padding: 0 20px;
        }
      }
      .mt20 {
        margin-top: 20px;
      }
      .contract_form {
        :deep(.el-form-item) {
          padding: 10px 0px;
          margin-bottom: 0;
          border-bottom: 1px solid #eaeaea;
          .el-input .el-input__inner {
            border: 0;
          }
          &:last-child {
            border-bottom: 0;
            .el-form-item__content {
              text-align: right;
            }
          }
        }
        :deep(.el-form-item.is-error) {
          padding: 10px 0px 20px;
        }
      }
      .contact_btn {
        width: 100%;
        margin: 25px 0;
      }
    }
  }

  .el-popover {
    min-width: 200px;
    .cell-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 28px;
      font-size: 14px;
      font-weight: 300;

      .text1 {
        color: #33302d;
      }
      .text2 {
        color: #ff6b00;
      }
    }
  }
</style>
